package com.credit.web.basic;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.credit.context.CreditServletContext;
import com.credit.entity.CreditUserIdentify;
import com.credit.entity.CreditUserInfo;
import com.credit.exception.ErrorException;
import com.credit.service.CreditCouponService;
import com.credit.service.UserService;
import com.credit.util.BeanToMapUtil;
import com.credit.util.CodeValueUtil;
import com.credit.util.Constants;
import com.credit.util.ParamsConstant;
import com.credit.util.ParamsMapUtil;
import com.credit.web.basic.bean.ResBean;

@Controller
@RequestMapping("/user")
public class UserController {
	private static final SimpleDateFormat date_sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	@Autowired
	private UserService userService;
	@Autowired
	private CreditCouponService creditCouponService;
	
	@ResponseBody
	@RequestMapping(value = "/identify", method = RequestMethod.POST)
	public void identify(HttpServletRequest request, HttpServletResponse response) throws IllegalArgumentException, IllegalAccessException {
		
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		String realName = request.getParameter("realName");
		String avatar = request.getParameter("avatar");
		String IDNumber = request.getParameter("IDNumber");
		String currentCity = request.getParameter("currentCity");
		String identifyType = request.getParameter("identifyType");
		String identifyCompany = request.getParameter("identifyCompany");
		String companyName = request.getParameter("companyName");
		String material = request.getParameter("material");
		String certificateImg = request.getParameter("certificateImg");
		String aptitudeImg = request.getParameter("aptitudeImg");
		
		userInfo.setIdentifyCheck(CodeValueUtil.IDENTIFY_SUBMIT);
		userInfo.setRealName(realName);
		if(!StringUtils.isEmpty(avatar)&&!avatar.startsWith(ParamsConstant.QINIU_URL)){
			userInfo.setAvatar(ParamsConstant.QINIU_URL+avatar);
		}
		userInfo.setIDNumber(IDNumber);
		userInfo.setCurrentCity(currentCity);
		userInfo.setPushCity(currentCity);
		userInfo.setIdentifyType(Integer.valueOf(identifyType));
		userInfo.setCompanyType(Integer.valueOf(identifyCompany));
		userInfo.setCompanyName(companyName);
		userInfo.setMaterial(material);
		
		if(!StringUtils.isEmpty(certificateImg)&&!certificateImg.startsWith(ParamsConstant.QINIU_URL)){
			certificateImg = ParamsConstant.QINIU_URL+certificateImg;
		}
		
		userInfo.setCertificateImg(certificateImg);
		
		if(!StringUtils.isEmpty(aptitudeImg)&&!aptitudeImg.startsWith(ParamsConstant.QINIU_URL)){
			aptitudeImg = ParamsConstant.QINIU_URL+aptitudeImg;
		}
		
		userInfo.setAptitudeImg(aptitudeImg);
		userInfo.setUpdateTime(new Date());
		
		userService.identify(userInfo);
	}
	
	@ResponseBody
	@RequestMapping(value = "/setPushCity", method = RequestMethod.POST)
	public void setPushCity(HttpServletRequest request, HttpServletResponse response,@RequestParam("pushCity") String pushCity) throws IllegalArgumentException, IllegalAccessException, ErrorException {
		
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
         if(StringUtils.isEmpty(pushCity)){
        	 throw new ErrorException(Constants.PUSHCITY_NOTNULL_ERROR_CODE,Constants.PUSHCITY_NOTNULL_ERROR_DESC);
         }
		
		userService.updateUserInfo(userInfo);
	}
	
	@ResponseBody
	@RequestMapping(value = "/searchIdentify", method = RequestMethod.POST)
	public void searchIdentify(HttpServletRequest request, HttpServletResponse response)  {
		
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("realName", userInfo.getRealName());
		resBean.getData().put("avatar", userInfo.getAvatar());
		resBean.getData().put("IDNumber", userInfo.getIDNumber());
		resBean.getData().put("currentCity", userInfo.getCurrentCity());
		resBean.getData().put("identifyType", userInfo.getIdentifyType());
		resBean.getData().put("identifyCompany", userInfo.getCompanyType());
		resBean.getData().put("material", userInfo.getMaterial());
		resBean.getData().put("certificateImg", userInfo.getCertificateImg());
		resBean.getData().put("aptitudeImg", userInfo.getAptitudeImg());
		resBean.getData().put("identifyCheck", userInfo.getIdentifyCheck());
		resBean.getData().put("checkDesc", userInfo.getCheckDesc());
		resBean.getData().put("companyName", userInfo.getCompanyName());
		
		Map<String,Object> paramsMap = resBean.getData();
		
		ParamsMapUtil.replace(paramsMap);
		
		resBean.setData(paramsMap);
		
		CreditServletContext.setResBean(resBean);
		
	}
	
	/**
	 * 实名认证接口(用户端)
	 * @param request
	 * @param response
	 * @throws ErrorException 
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping(value = "/auth", method = RequestMethod.POST)
	public void auth(HttpServletRequest request, HttpServletResponse response) throws ErrorException, ParseException  {
		
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		String realName = request.getParameter("realName");
		String IDNum = request.getParameter("IDNum");
		String frontImg = request.getParameter("frontImg");
		String backImg = request.getParameter("backImg");
		String nation = request.getParameter("nation");
		String address = request.getParameter("address");
		String department = request.getParameter("department");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String sesameCredit = request.getParameter("sesameCredit");
		
		String id = request.getParameter("id");
		
		
		
		if(StringUtils.isEmpty(realName)){
			throw new ErrorException(Constants.REALNAME_NOTNULL_ERROR_CODE, Constants.REALNAME_NOTNULL_ERROR_DESC);
		}
		
		if(StringUtils.isEmpty(IDNum)){
			throw new ErrorException(Constants.IDNUM_NOTNULL_ERROR_CODE,Constants.IDNUM_NOTNULL_ERROR_DESC);
		}
		
		//校验稍后做
		if(!StringUtils.isEmpty(IDNum)&&!IDNum.matches(ParamsConstant.idcard_reg)){
			throw new ErrorException(Constants.IDCARD_VALIDATE_ERROR_CODE, Constants.IDCARD_VALIDATE_ERROR_DESC);
		}
		
		CreditUserIdentify identify = userService.findIdentifyByUId(userInfo.getId());/*userService.findUserByIdNoCache(userInfo.getId()).getCreditUserIdentify();*/
		
		if(identify ==null){
			identify = new CreditUserIdentify();
			
		}
		
		identify.setAddress(address);
		identify.setBackImg(backImg);
		identify.setDepartment(department);
		identify.setEndTime(date_sdf.parse(endTime));
		identify.setFrontImg(frontImg);
		identify.setIDNum(IDNum);
		identify.setNation(nation);
		identify.setRealName(realName);
		identify.setStartTime(date_sdf.parse(startTime));
		identify.setUserId(userInfo.getId());
		//identify.setUserInfo(userInfo);
		
		userInfo.setIdentifyCheck(CodeValueUtil.IDENTIFY_CHECK);
		if(!StringUtils.isEmpty(sesameCredit)){
			userInfo.setSesameCredit(Integer.valueOf(sesameCredit));
		}
		userService.authUser(identify,userInfo);
		
	}
	

	/**
	 * 认证查询接口(用户端)
	 * @param request
	 * @param response
	 * @throws ErrorException
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	@ResponseBody
	@RequestMapping(value = "/authQuery", method = RequestMethod.POST)
	public void authQuery(HttpServletRequest request, HttpServletResponse response) throws  ErrorException, IllegalArgumentException, IllegalAccessException{
		
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		CreditUserIdentify userIdentify = userService.findIdentifyByUId(userInfo.getId());/*userService.findUserByIdNoCache(userInfo.getId()).getCreditUserIdentify();*/
		
		
		Map<String,Object> returnMap = new HashMap<String, Object>();
		if(userIdentify !=null){
			returnMap = BeanToMapUtil.getMap(userIdentify);
			returnMap.put("sesameCredit", userInfo.getSesameCredit());
			returnMap.put("userId",userInfo.getId());
		}
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("identify", returnMap);
		CreditServletContext.setResBean(resBean);
			
	}
	
	@ResponseBody
	@RequestMapping(value = "/getUser", method = RequestMethod.POST)
	public void getUser(HttpServletRequest request, HttpServletResponse response) throws  ErrorException, IllegalArgumentException, IllegalAccessException{
		
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		Map<String,Object> returnMap  = BeanToMapUtil.getMap(userInfo);
		
		//查询未使用的优惠券数量
		Integer couponCount = creditCouponService.getCouponCountByUserId(userInfo.getId());
		returnMap.put("couponCount", couponCount);
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("userInfo", returnMap);
		CreditServletContext.setResBean(resBean);
			
	}
	
/*	*//**
	 * 用户认证审核
	 * @param request
	 * @param ids
	 * @return
	 *//*
	@ResponseBody
	@RequestMapping(value = "/checkPermit", method = RequestMethod.POST)
	public void checkPermit(HttpServletRequest request, @PathVariable("ids") String ids){
		
        String[] idstrs = ids.split("_");
		
		for (String id : idstrs) {
			userService.checkPermit(Long.valueOf(id));
		}
		
	}*/
	
}
